<!-- 角色列表 -->
<template>
    <el-row>
        <el-col class="page-top-btn-group">
            <el-button size="small" type="primary" icon="Plus" @click="showAddForm">
                新增
            </el-button>

        </el-col>
    </el-row>

    <el-row v-for="roles in roleList">
        <el-col :span="6" v-for="role in roles" class="m-b-20">
            <el-text class="pointer" type="primary" @click="showEditForm(role)">{{ role.name }}</el-text>
            <el-icon size="small" class="m-l-5 m-r-5 pointer" @click="showBindRouteForm(role)">
                <Edit />
            </el-icon>

            <el-icon size="small" class="m-l-5 m-r-5 pointer" @click="delRole(role)">
                <Delete />
            </el-icon>
        </el-col>
    </el-row>


    <!-- 新增弹框 -->
    <el-dialog v-model="addForm.showDialog" title="新增角色">
        <el-form ref="addFormRef" :model="addForm.formData" label-width="auto" :rules="addForm.rules">
            <el-form-item label="名称" prop="name">
                <el-input v-model="addForm.formData.name"></el-input>
            </el-form-item>

            <el-button @click="addSub(addFormRef)" :loading="addForm.onSubmiting">提交</el-button>
        </el-form>
    </el-dialog>

    <!-- 编辑弹框 -->
    <el-dialog v-model="editForm.showDialog" title="编辑角色">
        <el-form ref="editFormRef" :model="editForm.formData" label-width="auto" :rules="editForm.rules">
            <el-form-item label="名称" prop="name">
                <el-input v-model="editForm.formData.name"></el-input>
            </el-form-item>

            <el-button @click="editSub(editFormRef)" :loading="editForm.onSubmiting">更新</el-button>
        </el-form>
    </el-dialog>

    <!-- 角色的路由绑定 -->
    <el-dialog v-model="bindRouteForm.showDialog" title="绑定路由" @opened="bindRouteFormOpened">


        <el-tree ref="routeTreeRef" :data="routes" node-key="id" show-checkbox :expand-on-click-node="false">
            <template #default="{ data }">
                <span>{{ data.name }}</span>
                <span class="route-type" :class="'route-type-' + data.type">{{ renderRouteType(data.type) }}</span>

            </template>
        </el-tree>

        <el-button @click="bindRoutesSub()" :loading="bindRouteForm.onSubmiting">更新</el-button>

    </el-dialog>
</template>

<script setup>

import { ref, onMounted } from 'vue'
import routeApi from '@/api/route'
import RouteCode from '@/constants/RouteCode'
import roleApi from '@/api/role'
import msgUtil from '@/utils/msgUtil'
import arr from '@/utils/arr'

const routeTreeRef = ref(null)
const addFormRef = ref()
const editFormRef = ref()

// 路由树形数据
const routes = ref([])

const roleList = ref([])

const initAddForm = () => {
    return {
        name: ''
    }
}

// 渲染类型文字
function renderRouteType(type) {
    return RouteCode.textOfType(type)
}

// 加载所有路由
function loadAllRoute() {
    routeApi.all().then(res => {
        msgUtil.alertIfError(res).then(apiRes => {
            routes.value = apiRes.data.tree;
        })
    })
}

const addForm = ref({
    showDialog: false,
    onSubmiting: false,
    formData: initAddForm(),
    rules: {
        name: [{ required: true, message: '必填' }],
    }
})

const editForm = ref({
    showDialog: false,
    onSubmiting: false,
    formData: {},
    rules: {
        name: [{ required: true, message: '必填' }],
    }
})



// 弹窗新增
function showAddForm() {
    addForm.value.showDialog = true
    addForm.value.formData = initAddForm()
}

// 提交新增
function addSub(formEl) {

    formEl.validate((valid, fields) => {
        if (!valid) {
            return;
        }
        if (addForm.value.onSubmiting) {
            return;
        }
        addForm.value.onSubmiting = true;

        roleApi.add(addForm.value.formData).then(res => {
            msgUtil.handleApiRes(res, {
                onApiSuccess() {
                    initPage();
                    addForm.value.showDialog = false
                }
            })
        }).finally(() => {
            addForm.value.onSubmiting = false;
        })
    })

}

// 弹窗编辑
function showEditForm(data) {
    editForm.value.showDialog = true
    editForm.value.formData = data
}

// 提交编辑
function editSub(formEl) {

    formEl.validate((valid, fields) => {
        if (!valid) {
            return;
        }
        if (editForm.value.onSubmiting) {
            return;
        }
        editForm.value.onSubmiting = true;

        roleApi.update(editForm.value.formData).then(res => {
            msgUtil.handleApiRes(res, {
                onApiSuccess() {
                    initPage();
                    editForm.value.showDialog = false
                }
            })
        }).finally(() => {
            editForm.value.onSubmiting = false;
        })
    })
}

// 绑定路由数据
const bindRouteForm = ref({
    showDialog: false,
    onSubmiting: false,
    formData: {
        id: 0,
        route_ids: []
    },
})

// 显示绑定路由弹框
function showBindRouteForm(role) {
    loadAllRoute()
    roleApi.detail(role.id).then(res => {
        msgUtil.alertIfError(res).then(() => {

            bindRouteForm.value.formData.id = role.id;
            bindRouteForm.value.formData.route_ids = res.data.routes;
            bindRouteForm.value.showDialog = true
        })
    })

}

// diaolog 是懒加载的，打开之前没有里面的dom引用
function bindRouteFormOpened() {
    // 设置选中的id
    routeTreeRef.value.setCheckedKeys(bindRouteForm.value.formData.route_ids)
}

// 提交绑定路由数据
function bindRoutesSub() {
    let keys = routeTreeRef.value.getCheckedKeys();
    if (keys.length === 0) {
        msgUtil.warnMsg({
            message: '请选择要绑定的路由'
        })
        return;
    }
    if (bindRouteForm.value.onSubmiting) {
        return;
    }
    bindRouteForm.value.onSubmiting = true;
    bindRouteForm.value.formData.route_ids = keys;

    roleApi.bindRoutes(bindRouteForm.value.formData)
        .then(res => {
            msgUtil.handleApiRes(res, {
                onApiSuccess() {
                    initPage();
                    bindRouteForm.value.showDialog = false
                }
            })
        })
        .finally(() => {
            bindRouteForm.value.onSubmiting = false;
        })
}

// 删除角色
function delRole(role) {
    msgUtil.dangerAction({
        message: '删除操作不可逆，删除该角色可能会影响与之相关的账号权限，确定要进行该操作吗？'
    })
        .then(res => {
            roleApi.del([role.id]).then(res => {
                msgUtil.handleApiRes(res, {
                    onApiSuccess() {
                        initPage();
                    }
                })
            })
        })
}

function initPage() {
    loadAllRole()
    // other method
}

function loadAllRole() {
    roleApi.all().then(res => {
        msgUtil.alertIfError(res).then(() => {
            roleList.value = arr.chunk(res.data.lists, 4)
        })
    })
}

onMounted(() => {
    initPage();
})
</script>

<style>
.route-type {
    font-size: small;
    margin-left: 20px;
}

.route-type-1 {
    color: #409EFF;
}

.route-type-2 {
    color: #33699f;
}

.route-type-3 {
    color: #67C23A;
}

.route-type-4 {
    color: #F56C6C;
}
</style>